/* API接口管理 */
class API {
    constructor() {
        this.baseURL = 'http://localhost:8000'; // 后端API地址
        this.endpoints = {
            // 用户相关
            login: '/api/auth/login',
            register: '/api/auth/register',
            logout: '/api/auth/logout',
            profile: '/api/user/profile',
            
            // 商品相关
            products: '/api/products',
            productDetail: '/api/products',
            search: '/api/products/search',
            categories: '/api/categories',
            
            // 购物车相关
            cart: '/api/cart',
            addToCart: '/api/cart/add',
            updateCart: '/api/cart/update',
            removeFromCart: '/api/cart/remove',
            
            // 订单相关
            orders: '/api/orders',
            createOrder: '/api/orders/create',
            orderDetail: '/api/orders',
            
            // 评价相关
            reviews: '/api/reviews',
            createReview: '/api/reviews/create',
            likeReview: '/api/reviews/like',
            
            // 物流相关
            logistics: '/api/logistics',
            tracking: '/api/logistics/tracking',
            
            // 卖家相关
            sellerProducts: '/api/seller/products',
            sellerShop: '/api/seller/shop',
            sellerStats: '/api/seller/stats'
        };
    }

    // 通用请求方法
    async request(endpoint, options = {}) {
        const url = `${this.baseURL}${endpoint}`;
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': this.getAuthToken(),
                'X-Username': this.getUsername()
            }
        };

        const config = { ...defaultOptions, ...options };
        
        try {
            const response = await fetch(url, config);
            
            // 获取响应文本
            const responseText = await response.text();
            
            // 尝试解析JSON
            let data;
            try {
                data = JSON.parse(responseText);
            } catch (e) {
                // 如果不是JSON，使用文本作为错误信息
                data = { success: false, error: responseText || `HTTP error! status: ${response.status}` };
            }
            
            // 如果状态码不是200-299，但响应中有错误信息，返回错误信息
            if (!response.ok) {
                return {
                    success: false,
                    error: data.error || data.message || `HTTP error! status: ${response.status}`
                };
            }
            
            // 直接返回API响应，保持原始格式
            return data;
        } catch (error) {
            console.error('API请求失败:', error);
            return { success: false, error: error.message };
        }
    }

    // 获取认证令牌
    getAuthToken() {
        const token = localStorage.getItem('authToken');
        return token ? `Bearer ${token}` : '';
    }

    // 获取当前用户名（用于后端识别用户）
    getUsername() {
        try {
            const raw = localStorage.getItem('currentUser') || localStorage.getItem('userData');
            if (!raw) return '';
            const user = JSON.parse(raw);
            return user && (user.username || user.user_name) ? (user.username || user.user_name) : '';
        } catch (e) {
            return '';
        }
    }

    // 用户认证相关
    async login(username, password) {
        return await this.request(this.endpoints.login, {
            method: 'POST',
            body: JSON.stringify({ username, password })
        });
    }

    async register(userData) {
        return await this.request(this.endpoints.register, {
            method: 'POST',
            body: JSON.stringify(userData)
        });
    }

    async logout() {
        return await this.request(this.endpoints.logout, {
            method: 'POST'
        });
    }

    async getProfile() {
        return await this.request(this.endpoints.profile);
    }

    // 商品相关
    async getProducts(params = {}) {
        const queryString = new URLSearchParams(params).toString();
        const endpoint = queryString ? `${this.endpoints.products}?${queryString}` : this.endpoints.products;
        return await this.request(endpoint);
    }

    async getProductDetail(productId) {
        return await this.request(`${this.endpoints.productDetail}/${productId}`);
    }

    async searchProducts(keyword, filters = {}) {
        return await this.request(this.endpoints.search, {
            method: 'POST',
            body: JSON.stringify({ keyword, filters })
        });
    }

    async getCategories() {
        return await this.request(this.endpoints.categories);
    }

    // 购物车相关
    async getCart() {
        return await this.request(this.endpoints.cart);
    }

    async addToCart(productId, quantity = 1) {
        return await this.request(this.endpoints.addToCart, {
            method: 'POST',
            body: JSON.stringify({ productId, quantity })
        });
    }

    async updateCartItem(productId, quantity) {
        return await this.request(this.endpoints.updateCart, {
            method: 'POST',
            body: JSON.stringify({ productId, quantity })
        });
    }

    async removeFromCart(productId) {
        return await this.request(this.endpoints.removeFromCart, {
            method: 'POST',
            body: JSON.stringify({ productId })
        });
    }

    // 订单相关
    async getOrders() {
        return await this.request(this.endpoints.orders);
    }

    async createOrder(orderData) {
        return await this.request(this.endpoints.createOrder, {
            method: 'POST',
            body: JSON.stringify(orderData)
        });
    }

    async getOrderDetail(orderId) {
        return await this.request(`${this.endpoints.orderDetail}/${orderId}`);
    }

    // 评价相关
    async getProductReviews(productId) {
        return await this.request(`${this.endpoints.reviews}/${productId}`);
    }

    async createReview(reviewData) {
        return await this.request(this.endpoints.createReview, {
            method: 'POST',
            body: JSON.stringify(reviewData)
        });
    }

    async likeReview(reviewId) {
        return await this.request(`${this.endpoints.likeReview}/${reviewId}`, {
            method: 'POST'
        });
    }

    // 物流相关
    async getLogistics(orderId) {
        return await this.request(`${this.endpoints.logistics}/${orderId}`);
    }

    async trackShipment(trackingNumber) {
        return await this.request(`${this.endpoints.tracking}/${trackingNumber}`);
    }

    // 卖家相关
    async getSellerProducts(username) {
        const qs = new URLSearchParams({ username }).toString();
        return await this.request(`${this.endpoints.sellerProducts}?${qs}`);
    }

    async addProduct(productData) {
        // 需要包含 username
        return await this.request(this.endpoints.sellerProducts, {
            method: 'POST',
            body: JSON.stringify(productData)
        });
    }

    async updateProduct(productId, productData) {
        // 需要包含 username
        return await this.request(`${this.endpoints.sellerProducts}/${productId}`, {
            method: 'PUT',
            body: JSON.stringify(productData)
        });
    }

    async updateProductDescription(productId, productData) {
        // 只更新商品描述
        return await this.request(`/api/products/${productId}/description`, {
            method: 'PUT',
            body: JSON.stringify(productData)
        });
    }

    async getProductSales(productId) {
        // 获取商品购买量
        return await this.request(`/api/products/${productId}/sales`);
    }

    async deleteProduct(productId, username) {
        const qs = new URLSearchParams({ username }).toString();
        return await this.request(`${this.endpoints.sellerProducts}/${productId}?${qs}`, {
            method: 'DELETE'
        });
    }

    async getSellerShop(username) {
        const qs = new URLSearchParams({ username }).toString();
        return await this.request(`${this.endpoints.sellerShop}?${qs}`);
    }

    async updateSellerShop(payload) {
        return await this.request(this.endpoints.sellerShop, {
            method: 'PUT',
            body: JSON.stringify(payload)
        });
    }

    async getSellerStats(username) {
        const qs = new URLSearchParams({ username }).toString();
        return await this.request(`${this.endpoints.sellerStats}?${qs}`);
    }

    // 管理员相关API
    async getAdminUsers() {
        return await this.request('/api/admin/users');
    }

    async deleteAdminUser(username) {
        return await this.request(`/api/admin/users/${username}`, {
            method: 'DELETE'
        });
    }

    async getAdminDailyOrders() {
        return await this.request('/api/admin/daily-orders');
    }
}

// 创建全局API实例
window.api = new API();
